//
//  FileDownLoadNetWork.m
//  work1
//
//  Created by zhoudong on 2018/5/17.
//  Copyright © 2018年 session. All rights reserved.
//

#import "FileDownLoadNetWork.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import <CommonCrypto/CommonDigest.h>

@implementation FileDownLoadNetWork{
    
  
    BOOL mIsSuspend;
    NSString* fileName;
}
//创建下载任务  下载文件
-(void)downFile:(NSString*)fileUrl isBreakpoint:(BOOL)breakpoint{
    if(fileUrl ==nil) return;

    self->fileName = [self md5:fileUrl];
    //1.创建NSURLSession,设置代理
    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    //2.创建task
    NSURL *url = [NSURL URLWithString:fileUrl];
    self.downloadTask = [self.session downloadTaskWithURL:url];
    
    if(breakpoint) [self getTmpDownProgress];
    
    //3.执行task
    [self.downloadTask resume];
}

//暂停下载
-(void)suspendDown{
    if(mIsSuspend){
        
        [self.downloadTask resume];
    }else{
        
         [self.downloadTask suspend];
    }
    
    mIsSuspend = !mIsSuspend;
}

//取消下载
-(void)cancelDown{
    //0101010010010101001010 000100101010
    [self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        
        [resumeData writeToFile:[self getTmpFileUrl] atomically:NO];
    }];
}


//获取上次下载的临时文件
-(void)getTmpDownProgress{
    
    NSFileManager * fm = [NSFileManager defaultManager];
    
    NSData* fileData = [fm contentsAtPath:[self getTmpFileUrl]];
    if(fileData){
        
        self.downloadTask = [self.session downloadTaskWithResumeData:fileData];
    }
}

//未下载完的临时文件url地址
-(NSString*)getTmpFileUrl{
    
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject];
    return  [NSString stringWithFormat:@"%@/%@.tmp",documentsPath,self->fileName];
    
}


/*
 1.当接收到下载数据的时候调用,可以在该方法中监听文件下载的进度
 该方法会被调用多次
 totalBytesWritten:已经写入到文件中的数据大小
 totalBytesExpectedToWrite:目前文件的总大小
 bytesWritten:本次下载的文件数据大小
 */
-(void)URLSession:(nonnull NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
     float downPro  = 1.0 * totalBytesWritten/totalBytesExpectedToWrite;
     if(self.myDeleate!= nil)
         [self.myDeleate backDownprogress:downPro];
    
}

/*
 2.下载完成之后调用该方法
 */
-(void)URLSession:(nonnull NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(nonnull NSURL *)location{
    
    
    //存储本地
    //1.获取Documents文件夹路径 （不要将视频、音频等较大资源存储在Caches路径下）
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject];
    
    //2.创建资源存储路径
    NSString *appendPath = [NSString stringWithFormat:@"/%@.mp4",self->fileName];
    NSString *file = [documentsPath stringByAppendingString:appendPath];
    
    //3.将下载好的视频资源存储在路径下
      NSFileManager *manager = [NSFileManager defaultManager];
    //删除之前相同路径的文件
     [manager removeItemAtPath:file error:nil];
    
    //将视频资源从原有路径移动到自己指定的路径
    BOOL success = [manager copyItemAtPath:location.path toPath:file error:nil];
    
    if (success) {
        dispatch_async(dispatch_get_main_queue(), ^{

            NSURL *url = [[NSURL alloc]initFileURLWithPath:file];
            if(self.myDeleate!= nil)
                [self.myDeleate downSucceed:url];
        });
     }
}


/*
 4.请求完成之后调用
 如果请求失败，那么error有值
 */

//下载失败调用
-(void)URLSession:(nonnull NSURLSession *)session task:(nonnull NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error{
    
    if(error!=nil&& self.myDeleate!= nil && error.code != -999)
        [self.myDeleate downError:error];
}

//用url获取文件名称
- (NSString *)md5:(NSString *)string{
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02X", digest[i]];
    }
    
    return result;
}


@end
